package org.cmg.study.spring;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author CMG
 * @version 1.0
 * @cLassName PersonDaoImpl
 * @description
 * @date 2021/9/1 13:48
 **/
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = false)
public class PersonDaoImpl implements PersonDao {
    private JdbcTemplate jdbcTemplate;
    private PersonDao personDao;

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public PersonDao getPersonDao() {
        return personDao;
    }

    public void setPersonDao(PersonDao personDao) {
        this.personDao = personDao;
    }

    public void setDataSource(DataSource dataSource){
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    public void createPersonTable() {
        this.jdbcTemplate.execute("CREATE TABLE `person` (`id` int(11) NOT NULL AUTO_INCREMENT," +
                "`name` varchar(50)DEFAULT NULL," +
                "`age` int(11) DEFAULT NULL," +
                "PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8;");
    }

    @Override
    public void savePerson(Person person) {
        try{
            this.jdbcTemplate.update("INSERT INTO PERSON(NAME,age) VALUES (?,?)", person.getName(), person.getAge());
            this.jdbcTemplate.update("INSERT INTO PERSON(NAME,age) VALUES (?,?)", "google", 16);
            throw new RuntimeException("simulate Error condition");
        }catch (Exception e){
            System.out.println("Error in creating record, rolling back");
            throw e;
        }
    }

    @Override
    public List<Person> listPerson() {
        List<Person> persons = this.jdbcTemplate.query("SELECT NAME,age FROM PERSON", new RowMapper<Person>() {
            public Person mapRow(ResultSet rs, int rowNum) throws SQLException {
                Person person = new Person();
                person.setName(rs.getString("name"));
                person.setAge(rs.getInt("age"));
                return person;
            }
        });
        return persons;
    }
}
